#!/usr/bin/env node

// 天气预报
const http = require('http'),
  log = console.log
let baseURL = 'http://t.weather.sojson.com/api/weather/city/';
const cityCodes = {
  '北京': 101010100,
  '上海': 101020100,
  '天津': 101030100,
  '重庆': 101040100,
  '香港': 101320101,
  '澳门': 101330101,
  '石家庄': 101090101,
}
//客户端请求curl http://localhost:8080/北京

const cache = {
  
}
http.createServer((req,myRes) => {
  //1.get city name from url
  // log(decode(req.url));
  const cityName = decodeURI(req.url).slice(1);
  // log(cityName);

  //2.query city code from dictionary
  const cityCode = cityCodes[cityName];
  // log(cityCode);

  //3.request HTTP weather API
  const url = baseURL + cityCode;
  myRes.setHeader('Content-Type', 'application/json;charset=UTF-8');
  // log(url);
  if(cache[cityName]){
    myRes.end(cache[cityName]);
    return;
  }
  if(newDate()) cache = {}
  http.get(url, res => {
    let data = '';
    res.on('data', chunk => data += chunk);
    res.on('end', () =>{
      cache[cityName] = data;
      myRes.end(data);
    });
  });
}).listen(8080);

